package main

import (
	"context"
	"fmt"
	"go_rpc/grpc_test/proto"
	"google.golang.org/grpc"
	"net"
)

type Server struct {
	proto.UnimplementedGreeterServer
}

func (s *Server) mustEmbedUnimplementedGreeterServer() {
	panic("implement me")
}

func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {
	return &proto.HelloReply{
		Message: "hello" + request.Name,
	}, nil
}

func main() {
	// 实现拦截器
	interceptor := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
		fmt.Println("接收到了一个新的请求")
		res, err := handler(ctx, req)
		if err != nil {
			fmt.Println("异常:", err.Error())
			panic(err)
		}
		fmt.Println("请求处理完成:")
		fmt.Println(res)
		return res, err
	}

	opt := grpc.UnaryInterceptor(interceptor)
	g := grpc.NewServer(opt)
	//修复错误
	proto.RegisterGreeterServer(g, &Server{})
	lis, err := net.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		panic("failed to listen: " + err.Error())
	}
	_ = g.Serve(lis)
}
